package com.feng.filter;

import com.alibaba.fastjson.JSON;
import com.feng.domain.ResponseResult;
import com.feng.domain.entity.LoginUser;
import com.feng.domain.enums.AppHttpCodeEnum;
import com.feng.util.JwtUtil;
import com.feng.util.RedisCache;
import com.feng.util.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    //不能在Filter抛出异常，因为security异常处理处理的是controller层的异常，
    // 而Filter不会被Security异常处理捕获，需要手动将错误信息以json形式返回给前端
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token
        String token = httpServletRequest.getHeader("token");
        if(!StringUtils.hasText(token)){
            //前端如果有传token的值，且值没有内容
            //token 为空，说明该页面不需要携带token不需要认证，直接放行
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //解析获取userid
        Claims claims = null;
        try {
            //解析token
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token超时 token非法
            //响应告诉前端需要重新登录
            ResponseResult result=ResponseResult.errorResult((AppHttpCodeEnum.NEED_LOGIN));
            String s = JSON.toJSONString(result);

            WebUtils.renderString(httpServletResponse,s);
            return;
        }
        String userId = claims.getSubject();
        //从redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
        //如果获取不到
        if(Objects.isNull(loginUser)){
            //说明redis中的值过期了，需要重新登录
            ResponseResult result=ResponseResult.errorResult((AppHttpCodeEnum.NEED_LOGIN));
            String s = JSON.toJSONString(result);
            return;

        }
        //存入securityContextHolder
        //需要传入Authentication的实现类
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginUser,null,null);
        //TODO 获取权限信息封装到Authentication中
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
       //执行完需要进行放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
        //需要配到security配置类中才能生效
    }
}
